﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ext.Net;
using XMK.Tadong.StructuredData_IntoDb.Data;
using System.Data;
using System.Collections;
using FarPoint.Web.Spread;
using XMK.Tadong.Biz;
using System.IO;
using XMK.Tadong.Web.Language;

namespace XMK.Tadong.Web.Farpoint
{
    public partial class BasicData : FileExplorerPage
    {
        
        #region 本页面 传递及共用参数
        /*20100125张玉峰增加功能。如果用户每次要录入的是某个项目某个油田的数据，则在URL中添加以下参数：
         * FILTERCOLUMN=ID_PROJECT,ID_YQT&ID_PROJECT=16&ID_YQT=1
         * 如果本表的主键ID是类似于SQLSERVER的自增列，则在URL中添加以下参数：
         * AUTOCOLUMN=ID
         */
        public string m_FILTERCOLUMN = "";
        public Hashtable m_Filter = null;
        public string m_AUTOCOLUMN = "";
        public string m_CanImportData = "";//  =1 表示支持EXCEL数据导入功能
        public  string languageStr;
        private  string m_TotalPage;
        private string m_CurPageInfo;
        #endregion

        #region 数据编辑参数设计
        /// <summary>
        /// 网格数据是否重绘
        /// </summary>
        public bool bIsPaint = false;
        /// <summary>
        /// 存入在提示信息表中最大的记录号
        /// </summary>
        private int iErrorMessageNum
        {
            get { return (int)ViewState["iErrorMessageNum"]; }
            set { ViewState["iErrorMessageNum"] = value; }
        }
        /// <summary>
        /// 存入主键
        /// </summary>
        private string sPriKey
        {
            get { return (string)ViewState["sPriKey"]; }
            set { ViewState["sPriKey"] = value; }
        }
        /// <summary>
        /// 存入删除的数据
        /// </summary>
        private DataTable sDelTab
        {
            get { return (DataTable)ViewState["sDelTab"]; }
            set { ViewState["sDelTab"] = value; }
        }
        /// <summary>
        /// 存入发生错误的错误信息的转换对应列表
        /// </summary>
        private Hashtable aErrorMessage_list
        {
            get { return (Hashtable)ViewState["aErrorMessage_list"]; }
            set { ViewState["aErrorMessage_list"] = value; }
        }
        /// <summary>
        /// 根据异常信息返回友好的提示信息
        /// </summary>
        /// <param name="sError"></param>
        /// <returns></returns>
        private string GetErrorMessage(string sError)
        {
            if (aErrorMessage_list != null)
            {
                Hashtable hasErrorMess = aErrorMessage_list;
                foreach (DictionaryEntry item in hasErrorMess)
                {
                    if (sError.IndexOf(item.Key.ToString().Trim()) != -1)
                        return item.Value.ToString();
                }
            }
            return "";
        }
        /// <summary>
        /// 存入发生错误的错误信息列表
        /// </summary>
        private void ErrorMessage_ini()
        {
            Hashtable hasErrorMess = new Hashtable();
            hasErrorMess["违反了 PRIMARY KEY 约束"] = lang.Get("Primary key conflict,please check the row data");// "主键数据与已有的数据重复,请检查该行数据！";
            hasErrorMess["并发冲突"] = lang.Get("Concurrent conflict");// "并发冲突！";
            hasErrorMess["TABLE REFERENCE 约束"] = lang.Get("The foreign key constraint data error,foreign key has been deleted or does not exist.Please check the pull-down data source definition."); //"表外键约束数据有误,外键值已被删除或不存在,请检查下拉数据源定义！";
            hasErrorMess["COLUMN REFERENCE 约束"] = lang.Get("Column constraint data error,the values have been other records reference,can't change.");// "列约束数据有误,该键值已被其它记录数据引用，不可修改！";
            hasErrorMess["COLUMN FOREIGN KEY 约束"] = lang.Get("Column of the foreign key constraint data error,the foreign key value that has been deleted or does not exist.Please check the pull-down data source definition."); //"列外键约束数据有误,外键值已被删除或不存在,请检查下拉数据源定义！";
            hasErrorMess["未将对象引用设置到对象的实例"] = lang.Get("Object reference not set to an instance of an object,please check the ID data source in the data dictionary definition"); //"未将对象引用设置到对象的实例,请检查数据字典有关页面的数据源ID定义！";
            aErrorMessage_list = hasErrorMess;
        }

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
           
            #region 代码实现
            m_CanImportData = Request.QueryString["CANIMPORTDATA"];
            
            m_FILTERCOLUMN = Request.QueryString["FILTERCOLUMN"];
            if (!string.IsNullOrEmpty(m_FILTERCOLUMN))
            {
                m_Filter = new Hashtable();
                string[] split = m_FILTERCOLUMN.Split(',');
                foreach (string str in split)
                {
                    string strValue = Request.QueryString[str];
                    m_Filter.Add(str, strValue);
                }
            }
            //m_AUTOCOLUMN = Request.QueryString["AUTOCOLUMN"];

            if (!this.IsPostBack)
            {
                //前台id绑定-英文化
                this.btnReadData.DataBind();
                this.btnDownload.DataBind();
                this.btnXZAllMB.DataBind();
                this.ImBtn_cancle.DataBind();
                this.ImBtn_update.DataBind();
                this.ImBtn_pasteadd.DataBind();
                this.ImBtn_add.DataBind();
                this.ImBtn_save.DataBind();
                this.ImBtn_delete.DataBind();
                this.ImBtn_copy.DataBind();
                this.ImBtn_paste.DataBind();
                this.ImBtn_cut.DataBind();
                this.chkIgnoreKey.DataBind();
                this.btnFirstPage.DataBind();
                this.btnPreviousPage.DataBind();
                this.Label1.DataBind();
                this.btnNextPage.DataBind();
                this.btnLastPage.DataBind();
                this.btnRefresh.DataBind();
                this.Label2.DataBind();
                this.lbCurPageInfo.DataBind();

                m_TotalPage = lang.Get("page,total {0} page");//"页,共 {0} 页";
                m_CurPageInfo = lang.Get("Display {0} - {1} slips,total {2} slips");//"显示 {0} - {1} 条,共 {2} 条";
              

                //this.Session.Add("curstatus", "0");         //当前状态 0为首次打开，1 为数据库配置 2为直接录入 3为文件导入 10 其他状态；
                this.Session.Add("resultsql", "");          //数据源配置返回的sql查询语句
                this.Session.Add("oppfields", "");          //本地表和服务器表对应字段
                this.Session.Add("srcdb", "");              //本地数据库连接信息
                if (this.Request.QueryString["table_code"] == null || this.Request.QueryString["table_code"].ToString() == "")
                    return;
                else
                {
                    //获取当前待采集数据表
                    hidBDM.Value = HttpUtility.UrlDecode(this.Request.QueryString["table_code"].ToString());
                    GetOraginData();
                }
            }
           
            #endregion 代码实现
        }

        /// <summary>
        /// 获取当前表已有数据
        /// </summary>
        protected void GetOraginData()
        {
            #region 代码实现
            //样式设置
            FpSpread1.CommandBar.Visible = false;
            FpSpread1.EditModeReplace = true;
            //数据操作模式
            //_EditGrid.Sheets[0].OperationMode = FarPoint.Web.Spread.OperationMode.SingleSelect;

            FpSpread1.Sheets[0].ColumnHeader.DefaultStyle.Font.Size = 9;
            FpSpread1.Sheets[0].DefaultStyle.Font.Size = 9;
            FpSpread1.Sheets[0].Rows.Default.Height = 10;

            //FpSpread1.Sheets[0].AlternatingRows[0].BackColor = System.Drawing.Color.Linen;
            //排序设置
            FpSpread1.Sheets[0].AllowSort = true;
            FpSpread1.Sheets[0].AllowColumnMove = true;
            
            //绑定数据
            SetData();
            #endregion 代码实现
        }

        /// <summary>
        /// 数据绑定
        /// </summary>
        public void SetData()
        {
            #region 代码实现
            DataTable dt = null;

            DBTree db = new DBTree(Config.TadongDbProvider);
            dt = db.GetInputTableOraginData_Filter(hidBDM.Value, m_Filter);

            SetFpSpread(dt);

            if ((!string.IsNullOrEmpty(m_CanImportData)) && (m_CanImportData == "1"))
            { }
            else
            {
                //初始化数据采集动态表单 先取消这个自动生成录入框的功能
                //InitInputFieldTextBox();
            }
            #endregion 代码实现
        }

        private void SetFpSpread(DataTable p_dt)
        {
            #region 代码实现
            InitPageTool(p_dt.Rows.Count);
            BindDataModel(p_dt);

            //数据分页绑定
            if (p_dt == null || p_dt.Rows.Count == 0)
            {
                FpSpread1.Sheets[0].AddRows(0, 1);
            }
            #endregion 代码实现

        }

        /// <summary>    
        /// 将数据和数据字典对应
        /// </summary>
        /// <param name="dtsource"></param>
        protected void BindDataModel(DataTable dt)
        {
            #region 代码实现
            //绑定数据
            FarPoint.Web.Spread.Model.DefaultSheetDataModel model = new FarPoint.Web.Spread.Model.DefaultSheetDataModel(dt);
            FpSpread1.Sheets[0].DataModel = model;
            FpSpread1.Sheets[0].DataMember = "0";
            FpSpread1.Sheets[0].ColumnHeader.RowCount = 1;
            iErrorMessageNum = 0;//初始化提示信息的行数计数器
            ErrorMessage_ini();//初始化错误信息

            //设置删除的表session
            if (ViewState["sDelTab"] == null)
                ViewState["sDelTab"] = dt.Clone();

            //hidPopField.Value = ",";

            DBTree db = new DBTree(Config.TadongDbProvider);

            //获取字段项列表
            DataTable dtfield = db.GetInputFields(hidBDM.Value);

            if (dtfield == null || dtfield.Rows.Count == 0)
                return;
            {
                int iVisibleFieldCount = 0;
                int FdCnt = dtfield.Rows.Count;
                FieldCount.Value = FdCnt.ToString();
                bool isEN = true;
                if (this.Session["YY"] != null && this.Session["YY"].ToString() == "cn")
                {
                    isEN = false;
                }

                for (int i = 0; i < FdCnt; i++)
                {

                    //帮定对应数据列
                    //model.SetModelDataColumn(i, dtfield.Rows[i]["fldname"].ToString().Trim());
                    model.SetModelDataColumn(i, dtfield.Rows[i]["FIELD_CODE"].ToString().Trim());


                    //设置列头宽度
                    //if (dtfield.Rows[i]["columnwidth"].ToString().Trim() == "")
                    //{
                    //显示宽度
                    if (isEN)
                    {
                        string strENName = dtfield.Rows[i]["FIELD_ENNAME"].ToString().Trim();
                        if (string.IsNullOrEmpty(strENName))
                        {
                            strENName = dtfield.Rows[i]["FIELD_CODE"].ToString().Trim();
                        }
                        if (dtfield.Rows[i]["FIELD_SHOWWIDTH"].ToString().Trim() == "")
                        {
                            if (strENName.Length < 10)
                                FpSpread1.Sheets[0].Columns[i].Width = 70;
                            else
                                FpSpread1.Sheets[0].Columns[i].Width = 8 * strENName.Length;
                        }
                        else
                        {
                            int TitleLength = 8 * strENName.Length;
                            int DataLength = int.Parse(dtfield.Rows[i]["FIELD_SHOWWIDTH"].ToString().Trim());
                            if (TitleLength > DataLength)
                            {
                                FpSpread1.Sheets[0].Columns[i].Width = TitleLength;

                            }
                            else
                            {
                                FpSpread1.Sheets[0].Columns[i].Width = DataLength;
                            }
                        }
                    }
                    else
                    {
                        if (dtfield.Rows[i]["FIELD_SHOWWIDTH"].ToString().Trim() == "")
                        {
                            if (dtfield.Rows[i]["FIELD_NAME"].ToString().Trim().Length < 6)
                                FpSpread1.Sheets[0].Columns[i].Width = 70;
                            else
                                FpSpread1.Sheets[0].Columns[i].Width = 13 * dtfield.Rows[i]["FIELD_NAME"].ToString().Trim().Length;
                        }
                        else
                        {
                            int TitleLength = 13 * dtfield.Rows[i]["FIELD_NAME"].ToString().Trim().Length;
                            int DataLength = int.Parse(dtfield.Rows[i]["FIELD_SHOWWIDTH"].ToString().Trim());
                            if (TitleLength > DataLength)
                            {
                                FpSpread1.Sheets[0].Columns[i].Width = TitleLength;

                            }
                            else
                            {
                                FpSpread1.Sheets[0].Columns[i].Width = DataLength;
                            }
                        }
                    }

                    //设置标题中的列名
                    if (isEN)
                    {
                        string strENName = dtfield.Rows[i]["FIELD_ENNAME"].ToString().Trim();
                        if (string.IsNullOrEmpty(strENName))
                        {
                            strENName = dtfield.Rows[i]["FIELD_CODE"].ToString().Trim();
                        }
                        FpSpread1.Sheets[0].ColumnHeader.Cells[0, i].Value = strENName;
                    }
                    else
                    {
                        FpSpread1.Sheets[0].ColumnHeader.Cells[0, i].Value = dtfield.Rows[i]["FIELD_NAME"].ToString().Trim();
                    }


                    //列标题字体显示设置
                    FpSpread1.Sheets[0].ColumnHeader.Cells[0, i].Font.Bold = false;
                    FpSpread1.Sheets[0].ColumnHeader.Cells[0, i].Font.Size = 9;

                    string strPop = dtfield.Rows[i]["FIELD_POPWIN"].ToString();
                    string strShow = dtfield.Rows[i]["FIELD_SHOW"].ToString().Trim();
                    if (strShow == "0")
                    {
                        FpSpread1.Sheets[0].Columns[i].Visible = false;
                    }
                    else
                    {
                        FpSpread1.Sheets[0].Columns[i].Visible = true;
                        iVisibleFieldCount++;

                        if (!string.IsNullOrEmpty(strPop) && strPop.Trim().ToString() != "0")
                        {
                            //hidPopField.Value += iVisibleFieldCount.ToString() + ":" + strPop + ",";

                            for (int j = 0; j < dt.Rows.Count; j++)
                            {
                                FpSpread1.Sheets[0].Cells[j, i].Font.Size = FontUnit.Parse("0.1");
                            }
                        }

                    }


                    ////添加字段单位
                    //FpSpread1.Sheets[0].ColumnHeader.Cells[1, i].Value = dtfield.Rows[i]["unit"].ToString().Trim();

                    //主键锁定不修改（已经屏蔽了不能修改，现在可以修改主键）
                    if (dtfield.Rows[i]["FIELD_KEY"].ToString().Trim().ToUpper() == "1")
                    {
                        #region 代码实现
                        FpSpread1.Sheets[0].ColumnHeader.Cells[0, i].Font.Bold = true;
                        FpSpread1.Sheets[0].ColumnHeader.Cells[0, i].ForeColor = System.Drawing.Color.FromArgb(160, 82, 45);

                        FpSpread1.Sheets[0].FrozenColumnCount = i + 1;
                        //for (int j = 0; j < dt.Rows.Count; j++)
                        //{
                        //    FpSpread1.Sheets[0].Cells[j, i].Locked = true;
                        //}
                        sPriKey = sPriKey + dtfield.Rows[i]["FIELD_CODE"].ToString() + ",";
                        #endregion 代码实现
                    }

                    //待计算字段
                    //if (dtfield.Rows[i]["sfjs"].ToString().Trim() == "1")
                    //{
                    //    FpSpread1.Sheets[0].ColumnHeader.Cells[0, i].Font.Bold = true;
                    //    FpSpread1.Sheets[0].ColumnHeader.Cells[0, i].ForeColor = System.Drawing.Color.FromArgb(128, 0, 128);
                    //}
                }

                hidVisibleFieldCount.Value = iVisibleFieldCount.ToString();
                //根据字段类型设置单元格风格
                SetColumnCellStyle(dtfield);
            }
            #endregion 代码实现
        }

        /// <summary>
        /// 单元格风格设置
        /// </summary>
        /// <param name="dtfield"></param>
        protected void SetColumnCellStyle(DataTable dtfield)
        {
            #region 代码实现
            int FdCnt = dtfield.Rows.Count;
            //根据字段类型设置单元格风格
            for (int i = 0; i < FdCnt; i++)
            {
                string _field = dtfield.Rows[i]["FIELD_TYPE"].ToString();

                FarPoint.Web.Spread.StyleInfo style = new FarPoint.Web.Spread.StyleInfo();

                switch (_field.ToUpper().Trim())
                {
                    //文本类
                    case "C":
                        {
                            TextCellType txt = new TextCellType();
                            txt.AllowWrap = false;
                            style.CellType = txt;
                            //style.CellType = new FarPoint.Web.Spread.TextCellType();
                            if (!string.IsNullOrEmpty(dtfield.Rows[i]["FIELD_POPWIN"].ToString().Trim()) && dtfield.Rows[i]["FIELD_POPWIN"].ToString().Trim() != "0")
                            {
                                style.Font.Size = FontUnit.Parse("0.1");
                            }
                            break;
                        }
                    //浮点类
                    case "N":
                        {
                            style.CellType = new FarPoint.Web.Spread.DoubleCellType(-1000000000.00000000, 1000000000.00000000, lang.Get("Beyond the scope or contains non numeric character"));
                            break;
                        }
                    //日期类
                    case "D":
                        {
                            //采用日期验证
                            DateCellType dt = new DateCellType();

                            (dt as RegExpCellType).ValidationExpression = @"^((\d{2}(([02468][048])|([13579][26]))[\-\/]((((0?[13578])|(1[02]))[\-\/]((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\-\/]((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\-\/]((0?[1-9])|([1-2][0-9])))))|(\d{2}(([02468][1235679])|([13579][01345789]))[\-\/]((((0?[13578])|(1[02]))[\-\/]((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\-\/]((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\-\/]((0?[1-9])|(1[0-9])|(2[0-8]))))))(\s(((0?[0-9])|([1-2][0-3]))\:([0-5]?[0-9])((\s)|(\:([0-5]?[0-9])))))?$";
                            (dt as RegExpCellType).ErrorMessage = lang.Get("Enter the date is wrong, the correct format such as");// "输入日期有误,正确的格式如:2002-12-12 或 2002/12/12";

                            style.CellType = dt;

                            break;
                        }
                    //时间类
                    case "T":
                        {
                            TimeCellType dt = new TimeCellType();
                            style.CellType = dt;
                            break;
                        }

                }
                FpSpread1.Sheets[0].SetStyleInfo(-1, i, style);
            }
            //给下拉列表单元格赋值
            for (int i = 0; i < FdCnt; i++)
            {
                string _fielddatasource = dtfield.Rows[i]["FIELD_DATASOURCE"].ToString().Trim();

                if (_fielddatasource != "0" && _fielddatasource.Trim().ToString() != "")
                {
                    FarPoint.Web.Spread.StyleInfo style = new FarPoint.Web.Spread.StyleInfo();
                    if ((_fielddatasource.Length == 8) && (_fielddatasource.Substring(0, 8).ToUpper() == "CHECKBOX"))  //CHECKBOX,1,0
                    {
                        style.CellType = new FarPoint.Web.Spread.CheckBoxCellType();

                    }
                    else
                    {
                        //获取采集对应数据源
                        DataTable ds = XMK.Tadong.StructuredData_IntoDb.Data.StandardService.GetInputFieldDataSource(_fielddatasource);

                        if (ds.Columns.Count == 2)
                        {
                            string[] _values = new string[ds.Rows.Count];
                            string[] _items = new string[ds.Rows.Count];
                            for (int j = 0; j < ds.Rows.Count; j++)
                            {
                                _values[j] = Convert.ToString(ds.Rows[j].ItemArray[1]).Trim();
                                _items[j] = Convert.ToString(ds.Rows[j].ItemArray[0]).Trim();
                            }

                            style.CellType = new FarPoint.Web.Spread.ComboBoxCellType(_values, _items);

                        }
                    }
                    FpSpread1.Sheets[0].SetStyleInfo(-1, i, style);    //Apply the style 
                }
            }
            #endregion 代码实现
        }

        #region 扩展控件
        /// <summary>
        /// 扩展验证日期单元格 
        /// </summary>
        class DateCellType : FarPoint.Web.Spread.RegExpCellType
        {
            public override string Format(object value)
            {
                //获取年月日,去掉时间
                string sVal = value.ToString();
                string[] strA = sVal.Split(new char[1] { ' ' });
                return strA[0].ToString();
            }


        }
        /// <summary>
        /// 扩展验证日期单元格 
        /// </summary>
        class TimeCellType : FarPoint.Web.Spread.RegExpCellType
        {
            public override string Format(object value)
            {
                //获取年月日时间
                string sVal = value.ToString();
                return sVal;
            }
        }
        #endregion 扩展控件

        /// <summary>
        /// 添加错误信息
        /// </summary>
        /// <param name="sMessage"></param>
        public void AddErrorMess(string sMessage)
        {
            #region
            this.divFpSpread_Error.Visible = true;
            this.FpSpread_Error.Sheets[0].Rows.Add(iErrorMessageNum, 1);
            FpSpread_Error.Sheets[0].SetValue(iErrorMessageNum, 0, sMessage);
            FpSpread_Error.Sheets[0].Cells[iErrorMessageNum, 0].Locked = true;
            iErrorMessageNum = iErrorMessageNum + 1;
            this.FpSpread_Error.Sheets[0].PageSize = iErrorMessageNum;

            #endregion
        }

        #region 翻页工具栏
        
        //private  string m_TotalPage ="页,共 {0} 页";
        //private string m_CurPageInfo =  "显示 {0} - {1} 条,共 {2} 条";
        /// <summary>
        /// 初始化翻页工具栏状态
        /// </summary>
        /// <param name="curPage">当前页号</param>
        /// <param name="pageRowNum">页行数</param>
        /// <param name="totalRowNum">总行数</param>
        private void InitPageTool(int curPage, int pageRowNum = 20, int totalRowNum = 0)
        {
            
            #region
            //txtCurPage.Text = curPage.ToString();
            lblCurPage.Text = curPage.ToString();
            if (totalRowNum == 0)
            {
                btnFirstPage.Enabled = false;
                btnPreviousPage.Enabled = false;
                btnNextPage.Enabled = false;
                btnLastPage.Enabled = false;
                btnRefresh.Enabled = false;
                m_TotalPage = lang.Get("page,total {0} page");//"页,共 {0} 页";
                m_CurPageInfo = lang.Get("Display {0} - {1} slips,total {2} slips");//"显示 {0} - {1} 条,共 {2} 条";
                lbTotalPageNum.Text = string.Format(m_TotalPage, "");
                lbCurPageInfo.Text = string.Format(m_CurPageInfo, "", "", "");
            }
            else
            {
                int iTotalPageNum = 0;
                if (curPage > 1)
                {
                    btnFirstPage.Enabled = true;
                    btnPreviousPage.Enabled = true;
                    iTotalPageNum = totalRowNum / pageRowNum;
                    if (curPage < iTotalPageNum)
                    {
                        btnNextPage.Enabled = true;
                        btnLastPage.Enabled = true;
                    }
                    else
                    {
                        int iLast = totalRowNum % pageRowNum;
                        if (iLast > 0)
                        {
                            iTotalPageNum += 1;
                            if (iTotalPageNum > 2)
                            {
                                btnNextPage.Enabled = true;
                                btnLastPage.Enabled = true;
                            }
                            else
                            {
                                btnNextPage.Enabled = false;
                                btnLastPage.Enabled = false;
                            }
                        }
                        else
                        {
                            btnNextPage.Enabled = false;
                            btnLastPage.Enabled = false;
                        }
                    }
                }
                else
                {
                    btnFirstPage.Enabled = false;
                    btnPreviousPage.Enabled = false;
                    iTotalPageNum = totalRowNum / pageRowNum;
                    if (curPage < iTotalPageNum)
                    {
                        btnNextPage.Enabled = true;
                        btnLastPage.Enabled = true;
                    }
                    else
                    {
                        int iLast = totalRowNum % pageRowNum;
                        if (iLast > 0)
                        {
                            iTotalPageNum += 1;
                            if (iTotalPageNum > 1)
                            {
                                btnNextPage.Enabled = true;
                                btnLastPage.Enabled = true;
                            }
                            else
                            {
                                btnNextPage.Enabled = false;
                                btnLastPage.Enabled = false;
                            }
                        }
                        else
                        {
                            btnNextPage.Enabled = false;
                            btnLastPage.Enabled = false;
                        }
                    }
                }
                btnRefresh.Enabled = true;
                int iStratRow = (curPage - 1) * pageRowNum + 1;
                int iEndRow = curPage * pageRowNum;
                m_TotalPage = lang.Get("page,total {0} page");//"页,共 {0} 页";
                m_CurPageInfo = lang.Get("Display {0} - {1} slips,total {2} slips");//"显示 {0} - {1} 条,共 {2} 条";
                lbTotalPageNum.Text = string.Format(m_TotalPage, iTotalPageNum.ToString());
                lbCurPageInfo.Text = string.Format(m_CurPageInfo, iStratRow.ToString(), iEndRow.ToString(), totalRowNum.ToString());
            }

            #endregion
        }
        /// <summary>
        /// 当前行改变方法
        /// </summary>
        /// <param name="curPage">当前行</param>
        private void PageToolCurPageChange(int curPage)
        {
            #region
            int iTotalRowNum = GetCurTotalRowNum();
            int iPageRowNum = 20;
            if (cboYRowNum.SelectedValue != null)
            {
                iPageRowNum = Convert.ToInt32(cboYRowNum.SelectedValue.ToString());
            }
            FpSpread1.Sheets[0].PageSize = iPageRowNum;
            FpSpread1.GotoPage(curPage - 1);
            InitPageTool(curPage, iPageRowNum, iTotalRowNum);
            #endregion
        }
        /// <summary>
        /// 在页面加载时初始化工具栏
        /// </summary>
        /// <param name="totalRowNum">总行数</param>
        private void InitPageTool(int totalRowNum)
        {
            #region
            int iPageRowNum = 20;
            if (cboYRowNum.SelectedValue != null)
            {
                iPageRowNum = Convert.ToInt32(cboYRowNum.SelectedValue.ToString());
            }
            FpSpread1.Sheets[0].PageSize = iPageRowNum;
            FpSpread1.GotoPage(0);
            InitPageTool(1, iPageRowNum, totalRowNum);
            #endregion
        }


        /// <summary>
        /// 翻页工具栏第一页按钮click事件
        /// </summary>
        private void PageToolFirstPage()
        {
            #region
            int iCurPage = 1;
            PageToolCurPageChange(iCurPage);
            #endregion
        }
        /// <summary>
        /// 翻页工具栏上一页按钮click事件
        /// </summary>
        private void PageToolPreviousPage()
        {
            #region
            //int iCurPage = Convert.ToInt32(txtCurPage.Text.ToString());
            int iCurPage = Convert.ToInt32(lblCurPage.Text.ToString());
            iCurPage -= 1;
            PageToolCurPageChange(iCurPage);
            #endregion
        }
        /// <summary>
        /// 翻页工具栏下一页按钮click事件
        /// </summary>
        private void PageToolNextPage()
        {
            #region
            //int iCurPage = Convert.ToInt32(txtCurPage.Text.ToString());
            int iCurPage = Convert.ToInt32(lblCurPage.Text.ToString());
            iCurPage += 1;
            PageToolCurPageChange(iCurPage);
            #endregion
        }
        /// <summary>
        /// 翻页工具栏最后一页按钮click事件
        /// </summary>
        private void PageToolLastPage()
        {
            #region
            int iCurPage = GetTotalPageNum();
            PageToolCurPageChange(iCurPage);
            #endregion
        }

        /// <summary>
        /// 翻页工具栏刷新按钮click事件
        /// </summary>
        private void PageToolRefresh()
        {
            #region
            X.MessageBox.Alert("", lang.Get("Refresh is not implemented")).Show();
            #endregion
        }

        /// <summary>
        /// 选择分页数据
        /// </summary>
        private void TBSpacerSelect()
        {
            #region
            int iCurPage = 1;
            PageToolCurPageChange(iCurPage);
            #endregion
        }

        /// <summary>
        /// 获得总页数
        /// </summary>
        /// <returns></returns>
        private int GetTotalPageNum()
        {
            #region
            try
            {
                int iTotalRowNum = GetCurTotalRowNum();
                int iPageRowNum = Convert.ToInt32(cboYRowNum.SelectedValue.ToString());
                int iTotalPageNum = iTotalRowNum / iPageRowNum;
                if (iTotalRowNum % iPageRowNum > 0)
                {
                    iTotalPageNum += 1;
                }
                return iTotalPageNum;
            }
            catch
            {
                return 0;
            }
            #endregion
        }

        /// <summary>
        /// 获得总行数
        /// </summary>
        /// <returns></returns>
        private int GetCurTotalRowNum()
        {
            #region
            int iTotalRowNum = FpSpread1.ActiveSheetView.Rows.Count;
            return iTotalRowNum;
            #endregion
        }

        protected void btnFirstPage_Click(object sender, ImageClickEventArgs e)
        {
            PageToolFirstPage();
        }

        protected void btnPreviousPage_Click(object sender, ImageClickEventArgs e)
        {
            PageToolPreviousPage();
        }

        protected void btnNextPage_Click(object sender, ImageClickEventArgs e)
        {
            PageToolNextPage();
        }

        protected void btnLastPage_Click(object sender, ImageClickEventArgs e)
        {
            PageToolLastPage();
        }

        protected void cboYRowNum_SelectedIndexChanged(object sender, EventArgs e)
        {
            TBSpacerSelect();
        }
        #endregion

        protected void ImBtn_pasteadd_Click(object sender, ImageClickEventArgs e)
        {
            #region
            try
            {
                FpSpread spread = FpSpread1;
                //spread.SaveChanges();
                string data = "";
                data = hidKid.Value;
                if (data.Trim().Length == 0 || data == "data") return;

                int countcols = 1;
                int maxcols = 1;
                int countrows = 1;
                //
                //int startpos = 0;
                //
                //int length = 0;
                int col;
                int row;
                int startrow = spread.Sheets[0].RowCount;

                int startcol = 0;//spread.Sheets[0].ActiveColumn;
                for (int i = 0; i < data.Length; i++)
                {
                    string split = data.Substring(i, 1);
                    switch (split)
                    {
                        case "\r":
                            if (countcols > maxcols)
                                maxcols = countcols;
                            countcols = 0;
                            if (i < data.Length - 3)
                                countrows += 1;
                            break;
                        case "\t":
                            countcols += 1;
                            break;
                    }
                }

                countcols = maxcols;
                //修改了如果第一行是空行的判断
                if (spread.Rows.Count == 0)//? (Spread.IsBlankRow)
                {
                    //startrow--;
                    spread.Rows.Add(spread.Rows.Count, countrows);
                }
                else
                {
                    if (spread.Sheets[0].Cells[startrow - 1, 0].Text.ToString().Trim() == "")
                    {
                        startrow = startrow - 1;
                        spread.Rows.Add(spread.Rows.Count, countrows - 1);
                    }
                    else
                    {
                        spread.Rows.Add(spread.Rows.Count, countrows);
                    }
                }
                //startpos = 0;
                int iVisibleCols = 0;
                string data1 = data.Replace("\r\n", "\r");
                data1 = data1.Replace("\n", "\r");
                data = data1;
                string[] datas = data.Split('\r');
                //string s = "";
                for (row = startrow; row < startrow + countrows; row++)
                {
                    for (col = startcol; col < startcol + countcols; col++)
                    {
                        if (col >= spread.Sheets[0].Columns.Count) break;
                        if (datas[row - startrow].Trim().Length == 0) break;
                        while (!spread.Sheets[0].Columns[iVisibleCols].Visible)
                        {
                            iVisibleCols++;
                        }
                        string[] rows = datas[row - startrow].Split('\t');
                        if (col >= rows.Length) break;

                        try
                        {
                            spread.Sheets[0].Cells[row, iVisibleCols].Text = rows[col];
                        }
                        catch (Exception ex)
                        {
                            int r = row + 1;
                            int c = col + 1;
                            string strMessage =lang.Get("The")+r+lang.Get("row")+lang.Get("The")+c+lang.Get("column")+lang.Get("The data in question, as follows")+":"+ ex.Message; //"第" + r + "行" + " 第" + c + "列 " + "数据有问题,具体错误如下 ：" + ex.Message;
                            //System.Console.WriteLine(strMessage);
                            AddErrorMess(strMessage);
                            //return;
                        }
                        iVisibleCols++;
                        //}
                    }
                    iVisibleCols = 0;
                }

                //ImBtn_add.Enable = false;
                //ImBtn_pasteadd.Enable = false;
                ImBtn_cancle.Enabled = true;

                //int iPage = spread.Sheets[0].RowCount + 1;
                //int iPages = (int)(iPage / (spread.Sheets[0].PageSize));
                //spread.GotoPage(iPages);
                PageToolLastPage();
            }
            catch (Exception ex1)
            {
                //System.Console.WriteLine(ex1.ToString());
                AddErrorMess(ex1.ToString());
            }
            #endregion
        }

        protected void ImBtn_add_Click(object sender, ImageClickEventArgs e)
        {
            #region
            try
            {
                int iNum = FpSpread1.ActiveSheetView.Rows.Count;
                FpSpread1.ActiveSheetView.Rows.Add(iNum, 1);
                FpSpread1.ActiveSheetView.ActiveRow = iNum;
                FpSpread1.ActiveSheetView.ActiveColumn = 0;

                PageToolCurPageChange(GetTotalPageNum());

            }
            catch (Exception ex)
            {
                AddErrorMess(ex.ToString());
            }
            #endregion
        }

        protected void ImBtn_delete_Click(object sender, ImageClickEventArgs e)
        {
            #region
            try
            {
                FpSpread1.SaveChanges();
                int iddd = FpSpread1.ActiveSheetView.ActiveRow;
                //客户端获取当前所选行和行数,进行批量删除操作
                string[] Values = this.Selectrows.Value.Split('#');
                //int iStartRowIndex = (Convert.ToInt32(txtCurPage.Text) - 1) * Convert.ToInt32(cboYRowNum.SelectedValue) + Convert.ToInt32(Values[0]);
                int iStartRowIndex = (Convert.ToInt32(lblCurPage.Text) - 1) * Convert.ToInt32(cboYRowNum.SelectedValue) + Convert.ToInt32(Values[0]);
                int iRowCount = int.Parse(Values[2]);
                FpSpread1.Sheets[0].RemoveRows(iStartRowIndex, iRowCount);
                FpSpread1.SaveChanges();
                //int iNewPage = Convert.ToInt32(txtCurPage.Text);
                int iNewPage = Convert.ToInt32(lblCurPage.Text);
                if (iNewPage > GetTotalPageNum())
                {
                    iNewPage = GetTotalPageNum();
                }
                PageToolCurPageChange(iNewPage);
                //ImBtn_update.Enabled = false;
                //ImBtn_cancle.Enabled = false;
                ImBtn_save.Enabled = true;
            }
            catch (Exception ex)
            {
                AddErrorMess(ex.ToString());
            }
            #endregion
        }

        protected void ImBtn_update_Click(object sender, ImageClickEventArgs e)
        {
            #region 数据验证
            try
            {
                FpSpread1.SaveChanges();
                //检测数据表中的逻辑错误
                if (!CheckLogic(FpSpread1))
                    return;
                //else
                //{
                //    ImBtn_update.Enabled = false;
                //    ImBtn_cancle.Enabled = false;
                //}
                FpSpread1.SaveChanges();
            }
            catch (Exception ex)
            {
                AddErrorMess(ex.ToString());
            }
            #endregion
        }

        /// <summary>
        /// 数据逻辑检查
        /// </summary>
        /// <param name="Spread"></param>
        /// <returns></returns>
        private bool CheckLogic(FpSpread Spread)
        {
            #region 代码实现
            //清空错误的计算器
            iErrorMessageNum = 0;
            //清空错误表
            this.FpSpread_Error.Sheets[0].Rows.Remove(0, this.FpSpread_Error.Sheets[0].Rows.Count);

            System.Data.DataSet ds = (System.Data.DataSet)Spread.ActiveSheetView.DataSource;
            DataTable dt = ds.Tables[0];
            string sTemp;
            bool bReturn = true;
            int i = 0;

            //获得当前用户代码
            string sUserCode = "tww";                        //用户代码code
            //在此给三个固定列赋值
            for (int iRows = 0; iRows < dt.Rows.Count; iRows++)
            {
                try
                {
                    //添加三列固定列的值
                    string sDate = DateTime.Today.ToString("yyyyMMdd");
                    dt.Rows[iRows]["JZRQ"] = sDate;                 //加载日期应该是当前日期，将日期数据格式化一下
                    dt.Rows[iRows]["YHMC"] = sUserCode;             //当前用户代码
                    dt.Rows[iRows]["SHZT"] = "1";                   //审核状态1为提交状态
                }
                catch (Exception ex)
                {
                    System.Console.WriteLine(ex.Message.ToString());
                }
            }
            DBTree db = new DBTree(Config.TadongDbProvider);
            //获取效验列
            DataTable dtfield = db.GetInputFields(hidBDM.Value);

            int cnt = dtfield.Rows.Count;

            Hashtable hs_ChechNullColumn = new Hashtable();
            Hashtable hs_ChechLogicColumn = new Hashtable();
            Hashtable hs_ChechUniqueColumn = new Hashtable();
            //是否允许空,获取待检测字段列表
            for (int k = 0; k < cnt; k++)
            {
                //是否允许为空0为空 1不为空
                if (dtfield.Rows[k]["FIELD_NULL"].ToString().Trim() == "1")
                {
                    hs_ChechNullColumn[dtfield.Rows[k]["FIELD_CODE"].ToString().Trim()] = dtfield.Rows[k]["FIELD_CODE"].ToString().Trim();
                }
                //是否唯一
                if (dtfield.Rows[k]["FIELD_UNIQUE"].ToString().Trim() == "1")
                {
                    hs_ChechUniqueColumn[dtfield.Rows[k]["FIELD_CODE"].ToString().Trim()] = dtfield.Rows[k]["FIELD_CODE"].ToString().Trim();
                }
            }
            //检测逻辑关系
            foreach (DataRow drow in dt.Rows)
            {
                i++;
                System.Data.DataRowState rs = drow.RowState;
                if (rs == DataRowState.Deleted)
                {
                    i--;
                    continue;
                }
                else if (rs == DataRowState.Added || rs == DataRowState.Modified)
                {
                    //检测是否为空
                    foreach (DictionaryEntry aChechColumn in hs_ChechNullColumn)
                    {
                        if (drow[aChechColumn.Key.ToString().Trim()].ToString().Trim().Length == 0)
                        {
                            if (aChechColumn.Key.ToString().Trim() != "ID" && aChechColumn.Key.ToString().Trim() != "SDAID")
                            {
                                sTemp = aChechColumn.Value.ToString();
                                sTemp = lang.Get("The")+ Convert.ToString(i) + lang.Get("row")+lang.Get("Field") + sTemp +lang.Get("Value cannot be empty");
                                AddErrorMess(sTemp);
                                bReturn = false;
                            }
                        }
                    }

                    foreach (DictionaryEntry aUkCol in hs_ChechUniqueColumn)
                    {
                        string strCol = aUkCol.Key.ToString().Trim();
                        if (dt.Select(strCol + "='" + drow[strCol].ToString() + "'").Length > 1)
                        {
                            string strError = lang.Get("The") + Convert.ToString(i) + lang.Get("row") + lang.Get("Field") + aUkCol.Value.ToString() +lang.Get("Value repetition");
                            AddErrorMess(strError);
                            bReturn = false;
                        }
                    }
                }
            }
            if (bReturn)
            {
                AddErrorMess(lang.Get("Successful data detection"));
            }
            return bReturn;
            #endregion 代码实现
        }
        /// <summary>
        /// 保存数据
        /// </summary>
        private void DataSave()
        {
            #region 代码实现
            FarPoint.Web.Spread.Model.DefaultSheetDataModel model = (FarPoint.Web.Spread.Model.DefaultSheetDataModel)FpSpread1.Sheets[0].DataModel;
            //获取当前表格数据源
            System.Data.DataSet ds = (System.Data.DataSet)model.DataSource;
            DataTable dt_copy = new DataTable();
            DataTable dt;
            DataTable DtChanges_temp = null;
            ArrayList aErrorNum_temp = new ArrayList();
            ArrayList aErrorMess_temp = new ArrayList();
            ArrayList aErrorSate_temp = new ArrayList();

            try
            {
                //保存改变数据，但是不是提交到数据库
                this.FpSpread1.SaveChanges();

                Session["ViewState"] = this.FpSpread1.Sheets[0].SaveViewState();

                //为设置记录颜色（修改：黄；增加：绿；错误：红），保持原始的记录状态的数据表
                dt = ds.Tables[0];
                //dt_copy = dt.Copy();

                DataTable DtChanges = dt.GetChanges();

                //检测数据表中的逻辑错误
                if (!CheckLogic(this.FpSpread1))
                {
                    return;
                }

                DtChanges_temp = DtChanges;
                if (DtChanges == null)
                    return;
                else if (DtChanges.Rows.Count > 0)
                {
                    //更新数据
                    bool btrue = false;
                    dt_copy = dt.Copy();

                    if ((m_Filter != null) && (m_Filter.Count > 0))
                    {
                        btrue = XMK.Tadong.StructuredData_IntoDb.Data.StandardService.UpdateTable_Filter(dt_copy, hidBDM.Value, m_Filter, m_AUTOCOLUMN, this.chkIgnoreKey.Checked);
                    }
                    else if (!string.IsNullOrEmpty(m_AUTOCOLUMN))
                    {
                        btrue = XMK.Tadong.StructuredData_IntoDb.Data.StandardService.UpdateTable_Filter(dt_copy, hidBDM.Value, m_Filter, m_AUTOCOLUMN);
                    }
                    else
                    {
                        btrue = XMK.Tadong.StructuredData_IntoDb.Data.StandardService.UpdateTable(dt_copy, hidBDM.Value);
                    }
                    if (btrue)
                    {
                        ds.AcceptChanges();
                        GetOraginData();
                        this.FpSpread_Error.Sheets[0].Rows.Add(iErrorMessageNum, 1);
                        this.FpSpread_Error.Sheets[0].SetValue(iErrorMessageNum, 0, lang.Get("Successful data submitted"));
                    }
                    else
                    {
                        this.FpSpread_Error.Sheets[0].Rows.Add(iErrorMessageNum, 1);
                        this.FpSpread_Error.Sheets[0].SetValue(iErrorMessageNum, 0, lang.Get("Submit data error"));
                    }
                }
                FpSpread1.SaveChanges();
                PageToolFirstPage();

            }
            catch (Exception ex)
            {
                AddErrorMess(lang.Get("Submit data error")+":" + ex.Message);
            }

            for (int iCount = 0; iCount < aErrorNum_temp.Count; iCount++)
            {
                string sError = "";
                if (aErrorMess_temp[iCount].ToString().Trim() != "update_ok")
                {
                    sError = GetErrorMessage(aErrorMess_temp[iCount].ToString().Trim());
                    if (sError.Trim() != "") aErrorMess_temp[iCount] = sError;
                }
            }
            //保存时已设置颜色不要重画
            bIsPaint = true;
            #endregion 代码实现
        }

        protected void ImBtn_save_Click(object sender, ImageClickEventArgs e)
        {
            #region 保存数据
            try
            {
                DataSave();
            }
            catch (Exception ex)
            {
                AddErrorMess(ex.ToString());
            }
            #endregion
        }

        /// <summary>
        /// 读取本地文件数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnReadData_Click(object sender, EventArgs e)
        {
            #region 代码实现
            //获得当前用户代码
            //string sUserCode = "tww";                        //用户代码code

            string sFileName = FileUpload1.FileName.Trim().ToLower();
            if (sFileName.Length > 4)
            {
                string sXlsx = sFileName.Substring(sFileName.Length - 5);
                string sXls = sFileName.Substring(sFileName.Length - 4);
                if (sXlsx != ".xlsx" && sXls != ".xls")
                {
                    JScript.Alert(this.Page, lang.Get("This can only upload data that format is provided by our Excel template."));
                    return;
                }
            }
            else
            {
                JScript.Alert(this.Page, lang.Get("File error"));
                return;
            }

            if (string.IsNullOrEmpty(FileUpload1.FileName.Trim()))
            { }
            else
            {
                try
                {
                    ProcYC_File pf = new ProcYC_File();
                    pf.m_AccessoryUpload = this.FileUpload1;

                    DataTable dtExcel = pf.GetDataTableFromExcelFile();
                    if ((dtExcel == null) || (dtExcel.Rows.Count == 0))
                        return;
                    /////////////////////////////////////////////////////////////////
                    //获取字段项列表
                    DataTable dtfield = XMK.Tadong.StructuredData_IntoDb.Data.StandardService.GetInputFields(hidBDM.Value);
                    int FdCnt = dtfield.Rows.Count;

                    Hashtable htDM = new Hashtable();

                    //
                    for (int i = 0; i < FdCnt; i++)
                    {
                        string _fielddatasource = dtfield.Rows[i]["FIELD_DATASOURCE"].ToString().Trim();
                        string _fieldName = dtfield.Rows[i]["FIELD_CODE"].ToString().Trim();

                        if (_fielddatasource != "0" && _fielddatasource.Trim().ToString() != "")
                        {
                            if ((_fielddatasource.Length == 8) && (_fielddatasource.Substring(0, 8).ToUpper() == "CHECKBOX"))  //CHECKBOX,1,0
                            { }
                            else
                            {
                                //获取采集对应数据源
                                DataTable ds = XMK.Tadong.StructuredData_IntoDb.Data.StandardService.GetInputFieldDataSource(_fielddatasource);
                                htDM.Add(_fieldName, ds);
                            }

                        }
                    }


                    ////////////////////////////////////////////////////////////////
                    int iCurRow = 0;
                    DataTable dt = XMK.Tadong.StructuredData_IntoDb.Data.StandardService.GetInputTableNoData(hidBDM.Value);

                    foreach (DataRow drow in dtExcel.Rows)
                    {
                        iCurRow = iCurRow + 1;
                        DataRow newrow = dt.NewRow();
                        foreach (DataColumn col in dtExcel.Columns)
                        {
                            string strColName = col.ColumnName;
                            if ((drow[strColName] != null) && (!string.IsNullOrEmpty(drow[strColName].ToString())))
                            {
                                if (htDM[strColName] != null)
                                {
                                    DataTable dtDM = (DataTable)htDM[strColName];
                                    foreach (DataRow rDM in dtDM.Rows)
                                    {
                                        if (rDM[1].ToString() == drow[strColName].ToString())
                                        {
                                            newrow[strColName] = rDM[0];
                                            break;
                                        }
                                    }
                                }
                                else
                                {
                                    try
                                    {
                                        //给单元格赋值
                                        newrow[strColName.Trim().ToUpper().ToString()] = drow[strColName.ToUpper()].ToString().Trim();
                                    }
                                    catch (Exception ex)
                                    {
                                        //System.Console.WriteLine(ex.ToString());
                                        AddErrorMess(lang.Get("The") + iCurRow.ToString() + lang.Get("row") + "，'" + strColName.ToUpper() + lang.Get("column") + "，" + lang.Get("The current value") + "：" + drow[strColName.ToUpper()].ToString() + "。" + lang.Get("The error message") + "：" + ex.Message.ToString());
                                    }
                                }
                            }
                        }
                        //添加三列固定列的值
                        //string sDate = DateTime.Today.ToString("yyyyMMdd");
                        //newrow["JZRQ"] = sDate;                         //加载日期应该是当前日期，将日期数据格式化一下
                        //newrow["YHMC"] = sUserCode;                   //当前用户代码
                        //newrow["SHZT"] = "0";                         //审核状态0为保存状态

                        dt.Rows.Add(newrow);
                    }
                    SetFpSpread(dt);
                }
                catch (Exception ex)
                {
                    AddErrorMess(lang.Get("Please check the file format is in compliance with specification,The error message") + ex.Message.ToString());
                }

            }
            #endregion 代码实现
        }

        #region 配置数据源
        protected void btnRun_Click(object sender, EventArgs e)
        {
            DataTable dt = GetConfigDataSourceTable();
            //插入数据
            ConfigDataSourceReadData(dt);
        }
        /// <summary>
        /// 获得用户code
        /// </summary>
        /// <returns></returns>
        public string GetUserCode()
        {
            #region
            string sUserCode = "";                        //用户代码code
            sUserCode = "tww";
            //int iUserID;                                //用户id

            ////获得当前用户代码
            //if (!string.IsNullOrEmpty(this.Session["UserID"].ToString()))
            //{
            //    iUserID = System.Convert.ToInt32(this.Session["UserID"].ToString());
            //    JrscSoft.DAL.USER dalUser = new JrscSoft.DAL.USER();
            //    JrscSoft.Model.USER modelUser = dalUser.GetModel(iUserID);
            //    if (modelUser != null)
            //    {
            //        sUserCode = modelUser.USER_NAME.Trim().ToString();
            //    }
            //}
            return sUserCode;
            #endregion
        }


        /// <summary>
        /// 把从vfp和xls文件转换过了数据时出的错误信息显示出来
        /// </summary>
        /// <param name="dt">存储错误信息的表 （错误行数，错误列数）</param>
        private void ShowErrorInfo(System.Data.DataTable dt)
        {
            if (dt != null)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    AddErrorMess(lang.Get("The") + dt.Rows[i][0].ToString() + lang.Get("row") + "，" + lang.Get("The") + dt.Rows[i][1].ToString() + lang.Get("column") + lang.Get("data error") + lang.Get("The error message") + dt.Rows[i][2].ToString());
                }
            }
        }
        /// <summary>
        /// 获得通过配置数据源获得的table数据
        /// </summary>
        private DataTable GetConfigDataSourceTable()
        {
            #region
            DataSet ds = new DataSet();
            try
            {
                IConfigurature dbConf;
                string sResultSQL = this.Session["resultsql"].ToString();
                List<string> lstSrcDBInfo = (List<string>)this.Session["srcdb"];
                //List<ArrayList> lst2FieldInfo = (List<ArrayList>)this.Session["oppfields"];
                dbConf = ConnectionDB(lstSrcDBInfo[0].ToString());
                ds = dbConf.GetQueryResultDataSet(sResultSQL);
                ShowErrorInfo(ds.Tables["ErrorInfo"]);
                DeleteDB(lstSrcDBInfo[0].ToString());
                return ds.Tables[0];
            }
            catch (Exception ex)
            {
                AddErrorMess(lang.Get("Submit data error")+":" + ex.Message);
            }
            return ds.Tables[0];
            #endregion
        }
        /// <summary>
        /// 删除数据库临时文件
        /// </summary>
        /// <param name="DBType"></param>
        private void DeleteDB(string DBType)
        {
            #region
            string[] congInfo;

            try
            {
                switch (DBType)
                {
                    case "vpf":
                        congInfo = GetFileInfo();
                        File.Delete(congInfo[0].ToString());
                        break;
                    case "exl":
                        congInfo = GetFileInfo();
                        File.Delete(congInfo[0].ToString());
                        break;
                    default:
                        break;
                }

            }
            catch (Exception ex)
            {
            }
            #endregion
        }

        /// <summary>
        /// 连接数据库文件
        /// </summary>
        /// <returns>成功返回true，否则返回false</returns>
        private IConfigurature ConnectionDB(string DBType)
        {
            #region
            string[] congInfo;
            IConfigurature dbConf;

            try
            {
                switch (DBType)
                {
                    case "orl":
                        congInfo = GetDatabaseConInfo();
                        dbConf = new XMK.Tadong.StructuredData_IntoDb.Data.OracleConfigurature(congInfo, "");
                        return dbConf;
                    case "vpf":
                        congInfo = GetFileInfo();
                        dbConf = new XMK.Tadong.StructuredData_IntoDb.Data.VPFConfigurature(congInfo, "");
                        return dbConf;
                    case "exl":
                        congInfo = GetFileInfo();
                        dbConf = new XMK.Tadong.StructuredData_IntoDb.Data.ExcelConfigurature(congInfo);
                        return dbConf;
                    case "access":
                        congInfo = GetFileInfo();
                        dbConf = new XMK.Tadong.StructuredData_IntoDb.Data.AccessConfigurature(congInfo);
                        return dbConf;
                    default:
                        return null;
                }
            }
            catch (Exception ex)
            {
                JsAlert.Alert(lang.Get("Connect to the database file error"));
                return null;
            }
            #endregion
        }

        /// <summary>
        /// 获得Oracle数据库连接信息
        /// </summary>
        /// <returns>返回字符串数组</returns>
        private string[] GetDatabaseConInfo()
        {
            #region
            string[] info = new string[6];
            List<string> lstSrcDBInfo = (List<string>)this.Session["srcdb"];

            for (int i = 0; i < lstSrcDBInfo.Count - 1; i++)
            {
                info[i] = lstSrcDBInfo[i + 1].ToString();
            }
            return info;
            #endregion
        }

        /// <summary>
        /// 获取数据库文件名字串数组
        /// </summary>
        /// <returns></returns>
        private string[] GetFileInfo()
        {
            #region
            string[] info = new string[2];
            List<string> lstSrcDBInfo = (List<string>)this.Session["srcdb"];

            info[0] = lstSrcDBInfo[1].ToString();
            info[1] = lstSrcDBInfo[2].ToString();
            return info;
            #endregion
        }

        /// <summary>
        /// 把从配置数据源中获得的数据读入到新表中
        /// </summary>
        /// <param name="dtConfigData"></param>
        private void ConfigDataSourceReadData(DataTable dtConfigData)
        {
            #region
            int iCurRow = 0;                                          //当前行号
            string sUserCode = GetUserCode();                        //用户代码code

            if ((dtConfigData == null) || (dtConfigData.Rows.Count == 0))
                return;
            //获取字段项列表
            DataTable dtfield = StandardService.GetInputFields(hidBDM.Value);
            //int FdCnt = dtfield.Rows.Count;

            //获得字段对应信息
            List<ArrayList> lst2FieldInfo = (List<ArrayList>)this.Session["oppfields"];
            //获得一个没有数据的表
            DataTable dt = StandardService.GetInputTableNoData(hidBDM.Value);
            foreach (DataRow drow in dtConfigData.Rows)
            {
                iCurRow = iCurRow + 1;
                DataRow newrow = dt.NewRow();
                //int iCurCol = 0;
                foreach (DataColumn col in dtConfigData.Columns)
                {
                    string strColName = col.ColumnName;//本地数据表列名
                    //iCurCol = iCurCol + 1;
                    if ((drow[strColName] != null) && (!string.IsNullOrEmpty(drow[strColName].ToString())))
                    {
                        //对应字段并赋值
                        for (int i = 0; i < lst2FieldInfo.Count; i++)
                        {
                            if (lst2FieldInfo[i][1].ToString().ToUpper() == strColName.ToUpper())
                            {
                                string dtColName = lst2FieldInfo[i][0].ToString();//服务器表列名
                                try
                                {
                                    newrow[dtColName.Trim().ToString()] = drow[strColName.ToUpper()].ToString().Trim(); ;
                                }
                                catch (Exception ex)
                                {
                                    AddErrorMess(lang.Get("The") + iCurRow.ToString() + lang.Get("row") + "，'" + dtColName.ToUpper() + "'" + lang.Get("column") + "," + lang.Get("The current value") + "：" + drow[strColName.ToUpper()].ToString() + "。" + lang.Get("The error message") + "：" + ex.Message.ToString());
                                }
                            }
                        }
                    }
                }
                //添加三列固定列的值
                //string sDate = DateTime.Today.ToString("yyyyMMdd");
                //newrow["JZRQ"] = sDate;                         //加载日期应该是当前日期，将日期数据格式化一下
                //newrow["YHMC"] = sUserCode;                   //当前用户代码
                //newrow["SHZT"] = "0";                         //审核状态0为保存状态

                dt.Rows.Add(newrow);
            }
            SetFpSpread(dt);
            #endregion
        }
        #endregion

        #region 下载模板

        protected void btnDownload_Click(object sender, EventArgs e)
        {
            #region 下载模板
            try
            {
                string strExcelFile = "DataFile/ExcelTemplate/" + hidBDM.Value + ".xls";
                string strFilePath = Server.MapPath(strExcelFile);
                if (!File.Exists(strFilePath))
                {
                    JScript.Alert(this.Page, lang.Get("The current table") + hidBDM.Value + ".xls" + lang.Get("Template file does not exist, please contact the system administrator"));
                    return;
                }
                TransmitFile(strExcelFile);
            }
            catch (Exception ex)
            {
                JScript.Alert(this.Page, ex.Message);
            }
            #endregion
        }
        protected void btnXZAllMB_Click(object sender, EventArgs e)
        {
            #region 下载全部模板
            try
            {
                string strExcelFile = "DataFile/ExcelTemplate/allTemplate.rar";
                string strFilePath = Server.MapPath(strExcelFile);
                if (!File.Exists(strFilePath))
                {
                    JScript.Alert(this.Page, lang.Get("The current table") + hidBDM.Value + ".xls" + lang.Get("Template file does not exist, please contact the system administrator"));
                    return;
                }
                TransmitFile(strExcelFile);
            }
            catch (Exception ex)
            {
                JScript.Alert(this.Page, ex.Message);
            }
            #endregion
        }
        /// <summary>
        /// 使用微软的TransmitFile下载文件
        /// </summary>
        /// <param name="filePath">服务器相对路径</param>
        public void TransmitFile(string filePath)
        {
            #region

            try
            {
                filePath = Server.MapPath(filePath);
                if (File.Exists(filePath))
                {
                    FileInfo info = new FileInfo(filePath);
                    long fileSize = info.Length;
                    HttpContext.Current.Response.Clear();

                    //指定Http Mime格式为压缩包
                    HttpContext.Current.Response.ContentType = "application/x-zip-compressed";

                    // Http 协议中有专门的指令来告知浏览器, 本次响应的是一个需要下载的文件. 格式如下:
                    // Content-Disposition: attachment;filename=filename.txt
                    HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + Server.UrlEncode(info.FullName));
                    //不指明Content-Length用Flush的话不会显示下载进度   
                    HttpContext.Current.Response.AddHeader("Content-Length", fileSize.ToString());
                    HttpContext.Current.Response.TransmitFile(filePath, 0, fileSize);
                    HttpContext.Current.Response.Flush();
                }
            }
            catch (Exception ex)
            {
                JScript.Alert(this.Page, ex.Message);
            }
            finally
            {
                HttpContext.Current.Response.Close();
            }

            #endregion
        }

        #endregion

        protected void btnRefresh_Click(object sender, ImageClickEventArgs e)
        {
            #region 刷新数据
            try
            {
                SetData();
            }
            catch (Exception ex)
            {
                JScript.Alert(this.Page, ex.Message);
            }
            #endregion
        }



    }
}